import { defineStore } from 'pinia'
import {loginApi,user} from "../api/auth";

export interface IUserState{
    token:string
    username:string
    avatar:string
    permissions:string[]
    info:object
}
export const useStore = defineStore('app-user', {

    state: ():IUserState => ({
        token: localStorage.getItem('token')||'',
        username:'',
        avatar:'',
        permissions:[],
        info:{}
    }),
    getters:{
        getToken():string{
            return this.token
        },
        getUsername():string{
            return  this.username
        },
        getAvatar():string{
            return this.avatar
        },
        getPermissions():string[]{
            return this.permissions
        },
        getInfo():object{
            // if (!this.info?.id){
            //
            // }
                if(!this.info?.id) {
                    this.getUser()

            }// 判断 this.info 是否是空对象

            return this.info
        },

    },
    actions:{
        setToken(token:string) {
            localStorage.setItem('token',token)
            this.token = token


        },
        setUsername(username:string) {
            this.username = username
        },
        setAvatar(avatar:string) {
            this.avatar = avatar
        },
        setPermissions(permissions:string[]) {
            this.permissions = permissions
        },
        setInfo(info:object) {

            this.info = info

        },
        async login(info:object){
            try {
                const response = await loginApi(info);

                if (response.data.access_token){
                    this.setToken(response.data.access_token)
                    this.getUser()
                }


            }catch (error){

            }

        },
        async getUser(){
            try{

                const res = await user();
                console.log(res)

                this.setInfo(res.data)
                this.setAvatar(res.data.avatar_url)
                this.setUsername(res.data.name)
                return res.data
            } catch (error){

            }
        }
    }
})